/**
 * 权限缓存管理器
 * 
 * 实现权限信息的缓存机制，避免重复API调用，提升性能
 * 严格按照《智慧社区微服务架构总览.md》的权限体系标准实现
 * 
 * @author Wu.Liang
 * @date 2025-01-30
 */
import { ref, computed } from 'vue'
import { useUserStore } from '@/store/user'
import { propertyInfoApi } from '@/api/property/propertyInfo'

// 权限缓存状态
interface PermissionCache {
  // 公司信息缓存
  hasCompany: boolean | null
  companyId: number
  companyName: string
  companyCode: string
  
  // 权限信息缓存
  isSuperAdmin: boolean
  hasPropertyCompany: boolean
  dataScopeLevel: number
  
  // 缓存时间戳
  lastUpdateTime: number
  cacheExpireTime: number
  
  // 缓存状态
  isLoading: boolean
  isError: boolean
  errorMessage: string
}

// 全局权限缓存实例
const permissionCache = ref<PermissionCache>({
  hasCompany: null,
  companyId: 0,
  companyName: '',
  companyCode: '',
  isSuperAdmin: false,
  hasPropertyCompany: false,
  dataScopeLevel: 0,
  lastUpdateTime: 0,
  cacheExpireTime: 5 * 60 * 1000, // 5分钟缓存过期
  isLoading: false,
  isError: false,
  errorMessage: ''
})

/**
 * 权限缓存管理器
 */
export class PermissionCacheManager {
  /**
   * 检查缓存是否有效
   */
  static isCacheValid(): boolean {
    const now = Date.now()
    return permissionCache.value.lastUpdateTime > 0 && 
           (now - permissionCache.value.lastUpdateTime) < permissionCache.value.cacheExpireTime
  }
  
  /**
   * 检查缓存是否过期
   */
  static isCacheExpired(): boolean {
    const now = Date.now()
    return permissionCache.value.lastUpdateTime === 0 || 
           (now - permissionCache.value.lastUpdateTime) >= permissionCache.value.cacheExpireTime
  }
  
  /**
   * 获取缓存的权限信息
   */
  static getCachedPermission(): PermissionCache {
    return permissionCache.value
  }
  
  /**
   * 更新权限缓存
   */
  static updateCache(data: Partial<PermissionCache>): void {
    permissionCache.value = {
      ...permissionCache.value,
      ...data,
      lastUpdateTime: Date.now()
    }
    
    console.log('权限缓存已更新:', permissionCache.value)
  }
  
  /**
   * 清除权限缓存
   */
  static clearCache(): void {
    permissionCache.value = {
      hasCompany: null,
      companyId: 0,
      companyName: '',
      companyCode: '',
      isSuperAdmin: false,
      hasPropertyCompany: false,
      dataScopeLevel: 0,
      lastUpdateTime: 0,
      cacheExpireTime: 5 * 60 * 1000,
      isLoading: false,
      isError: false,
      errorMessage: ''
    }
    
    console.log('权限缓存已清除')
  }
  
  /**
   * 设置缓存加载状态
   */
  static setLoading(loading: boolean): void {
    permissionCache.value.isLoading = loading
  }
  
  /**
   * 设置缓存错误状态
   */
  static setError(error: boolean, message: string = ''): void {
    permissionCache.value.isError = error
    permissionCache.value.errorMessage = message
  }
  
  /**
   * 检查并更新公司信息（遵循权威文档标准）
   */
  static async checkAndUpdateCompanyInfo(): Promise<boolean> {
    const userStore = useUserStore()
    
    // 如果缓存有效，直接返回缓存的公司信息
    if (this.isCacheValid() && permissionCache.value.hasCompany !== null) {
      console.log('使用缓存的公司信息:', permissionCache.value.hasCompany)
      return permissionCache.value.hasCompany
    }
    
    // 如果正在加载，等待加载完成
    if (permissionCache.value.isLoading) {
      console.log('权限信息正在加载中，等待完成...')
      while (permissionCache.value.isLoading) {
        await new Promise(resolve => setTimeout(resolve, 100))
      }
      return permissionCache.value.hasCompany || false
    }
    
    // 开始加载
    this.setLoading(true)
    this.setError(false)
    
    try {
      console.log('开始检查用户是否关联物业公司...')
      
      // 调用权威文档指定的接口
      const hasCompanyRes = await propertyInfoApi.hasPropertyCompany()
      const hasCompany = hasCompanyRes.data || false
      
      console.log('用户关联物业公司状态:', hasCompany)
      
      if (hasCompany) {
        // 有关联物业公司，获取详细信息
        console.log('获取物业公司详细信息...')
        const infoRes = await propertyInfoApi.getCurrentUserPropertyInfo()
        const companyInfo = infoRes.data
        
        // 更新缓存
        this.updateCache({
          hasCompany: true,
          companyId: companyInfo?.propertyCompanyId || 0,
          companyName: companyInfo?.propertyCompanyName || '',
          companyCode: companyInfo?.propertyCompanyCode || '',
          hasPropertyCompany: true,
          dataScopeLevel: 1
        })
        
        // 同步更新userStore
        userStore.updateCompanyInfo({
          propertyCompanyId: companyInfo?.propertyCompanyId || 0,
          companyCode: companyInfo?.companyCode || '',
          companyName: companyInfo?.companyName || '',
          address: companyInfo?.address || '',
          introduction: companyInfo?.introduction || '',
          qualificationLevel: companyInfo?.qualificationLevel || '',
          serviceScope: companyInfo?.serviceScope || '',
          businessHours: companyInfo?.businessHours || '',
          serviceHotline: companyInfo?.serviceHotline || '',
          contactPerson: companyInfo?.contactPerson || '',
          contactPhone: companyInfo?.contactPhone || '',
          contactEmail: companyInfo?.contactEmail || '',
          paymentAccount: companyInfo?.paymentAccount || '',
          paymentBank: companyInfo?.paymentBank || ''
        })
        
        console.log('物业公司信息更新完成:', companyInfo)
      } else {
        // 无关联物业公司
        this.updateCache({
          hasCompany: false,
          companyId: 0,
          companyName: '',
          companyCode: '',
          hasPropertyCompany: false,
          dataScopeLevel: 0
        })
        
        // 同步更新userStore
        userStore.clearCompanyInfo()
        
        console.log('用户未关联物业公司')
      }
      
      return hasCompany
    } catch (error) {
      console.error('检查公司信息失败:', error)
      this.setError(true, error instanceof Error ? error.message : '未知错误')
      
      // 出错时设置为false，避免重复调用
      this.updateCache({
        hasCompany: false,
        companyId: 0,
        companyName: '',
        companyCode: '',
        hasPropertyCompany: false,
        dataScopeLevel: 0
      })
      
      return false
    } finally {
      this.setLoading(false)
    }
  }
  
  /**
   * 获取用户权限信息（带缓存）
   */
  static async getUserPermissionInfo(): Promise<PermissionCache> {
    const userStore = useUserStore()
    
    // 如果缓存有效，直接返回
    if (this.isCacheValid()) {
      console.log('使用缓存的权限信息')
      return permissionCache.value
    }
    
    // 检查并更新公司信息
    await this.checkAndUpdateCompanyInfo()
    
    // 更新超级管理员状态
    const isSuperAdmin = userStore.isSuperAdmin()
    
    this.updateCache({
      isSuperAdmin,
      hasPropertyCompany: permissionCache.value.hasCompany || false
    })
    
    return permissionCache.value
  }
  
  /**
   * 强制刷新权限缓存
   */
  static async forceRefresh(): Promise<PermissionCache> {
    console.log('强制刷新权限缓存...')
    this.clearCache()
    return await this.getUserPermissionInfo()
  }
}

// 导出计算属性
export const usePermissionCache = () => {
  const cache = computed(() => permissionCache.value)
  const isLoading = computed(() => permissionCache.value.isLoading)
  const isError = computed(() => permissionCache.value.isError)
  const errorMessage = computed(() => permissionCache.value.errorMessage)
  const isCacheValid = computed(() => PermissionCacheManager.isCacheValid())
  
  return {
    cache,
    isLoading,
    isError,
    errorMessage,
    isCacheValid,
    checkAndUpdateCompanyInfo: PermissionCacheManager.checkAndUpdateCompanyInfo.bind(PermissionCacheManager),
    getUserPermissionInfo: PermissionCacheManager.getUserPermissionInfo.bind(PermissionCacheManager),
    forceRefresh: PermissionCacheManager.forceRefresh.bind(PermissionCacheManager),
    clearCache: PermissionCacheManager.clearCache.bind(PermissionCacheManager)
  }
} 